package ai.people.netmon.auth.config;

import ai.people.core.security.entity.AuthenticationUser;
import ai.people.netmon.utils.JSONUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class CustomUserAuthenticationConverter extends DefaultUserAuthenticationConverter {
    @Autowired
    UserDetailsService userDetailsService;

    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        Map<String,Object> response = new LinkedHashMap<>();
        String name = authentication.getName();
        response.put("username", name);

        Object principal = authentication.getPrincipal();
        AuthenticationUser authenticationUser;
        if (principal instanceof AuthenticationUser) {
            authenticationUser = (AuthenticationUser) principal;
        } else {
            //refresh_token默认不去调用userdetailService获取用户信息，这里我们手动去调用，得到 UserJwt
            UserDetails userDetails = userDetailsService.loadUserByUsername(name);
            authenticationUser = (AuthenticationUser) userDetails;
        }
        //response.put("userId", userJwt.getUserId());
        Map map = JSONUtils.jsonToBean(JSONUtils.beanToJson(authenticationUser), Map.class);
        response.putAll(map);
        //if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
        //    response.put("authorities", AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        //}
        return response;
    }

}
